<?php
/**
 * Delete Action deletes a file from its fid (database)
 *   $_REQUEST['fid'] || $_REQUEST['sid']
 */
class DeleteAction extends CAction {

    public function run() {
        if (isset($_REQUEST['fid']) && is_numeric($_REQUEST['fid'])) {
            // Delete from database
            $file = File::model()->findByPk($_REQUEST['fid']);
            if (isset($file)) {
                if ($file->delete()) {
                    // Delete file
                    UploadUtils::deleteFile($file, PlUploadWidget::$fileDir);
                    $result["result"] = 0;
                } else {
                    $result["result"] = -1;
                    $result["message"] = Yii::t('amo', 'Could not delete file from db');
                }
            } else {
                $result["result"] = -1;
                $result["message"] = Yii::t('amo', 'No file with that fid');
            }
        } elseif (isset($_REQUEST['sid']) && is_numeric($_REQUEST['sid'])) {
            // Delete from session
            $sessionFiles = Yii::app()->session['temp_files'];
            $file = File::buildFromArray($sessionFiles[$_REQUEST['sid']]);
            unset($sessionFiles[$_REQUEST['sid']]);
            Yii::app()->session['temp_files'] = $sessionFiles;
            
            // Delete file
            UploadUtils::deleteFile($file, PlUploadWidget::$tempDir);
            
            $result["result"] = 0;
        } else {
            $result["result"] = -1;
            $result["message"] = Yii::t('amo', 'There is no file id (nor db and no session)');
        }
        echo CJSON::encode($result);
        exit(0); // To avoid loggers append things to request
    }
}
